package com.example.myfragmentmanager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.myfragmentmanager.fragment.IFragmentCallback;
import com.example.myfragmentmanager.fragment.ItemFragment;
import com.example.myfragmentmanager.fragment.MyFragment1;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取Change按钮并添加点击事件
        Button btnChange = findViewById(R.id.btn_change);
        btnChange.setOnClickListener(this);

        // 获取Replace按钮并添加点击事件
        Button btnReplace = findViewById(R.id.btn_replace);
        btnReplace.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_change) {
            Log.d(TAG, "onClick: Change");
            // Activity向Fragment传递数据
            Bundle data = new Bundle();
            data.putString("message", "Hello Fragment, I'm from MainActivity~~");
            MyFragment1 myFragment1 = new MyFragment1();
            myFragment1.setArguments(data);
            // 使用接口方式传递数据
            myFragment1.setFragmentCallback(new IFragmentCallback() {
                @Override
                public void setDataToActivity(String data) {
                    // Activity 接收Fragment发送过来的数据
                    Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG)
                            .show();
                }

                @Override
                public String getDataFromActivity() {
                    return "Hello, I'm from MainActivity~~~";
                }
            });
            replaceFragment(myFragment1);
        } else if(v.getId() == R.id.btn_replace) {
            Log.d(TAG, "onClick: Replace");
            replaceFragment(new ItemFragment());
        }
    }

    /**
     * 动态切换Fragment
     * @param fragment fragment片段
     */
    private void replaceFragment(Fragment fragment) {
        // 获取默认的 FragmentManager
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 创建Fragment事务管理器
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 完成替换
        transaction.replace(R.id.fl_main, fragment);
        // 添加至返回栈
        // 点击返回按钮，调用返回栈里面的数据
        transaction.addToBackStack(null);
        // 提交事务
        transaction.commit();
    }
}